import apiName from "./server";
import CONFIG from "../../config/config";
let vuethis = null;
let ajaxMethod = ['get', 'post', 'put'];
const api = {}
api.show = function(_this){
    vuethis = _this
}
ajaxMethod.forEach((method) => {
    // 超时时间
    const timeEnd = 60;
    let startTime = null;
    api[method] = function(uri, data = {}, success, failed){
        startTime = new Date();
        if(apiName[uri].interFaceType === "all") {
            // data = qs.stringify(data);
            let formData = new FormData();
            //传过去oss中的key 需要把目录dir和文件名key拼接起来带过去
            formData.append('key', data.key);
            //policy
            formData.append('policy', data.policy);
            //accessid
            formData.append('OSSAccessKeyId', data.accessid);
            //让oss返回服务器状态为200 默认是204
            formData.append('success_action_status', '200');
            //签名 signature
            formData.append('signature', data.signature);
            //callback
            formData.append('callback', data.callback);
            formData.append('url', data.url);
            //附件对象
            formData.append('file', data.imgFile);
            data = formData;
        } else {
            data = JSON.stringify(data);
        }
        // data = JSON.stringify(data);
        // vuethis.$Progress.start();
        let url = null;
        var xhr = null;
        if(apiName[uri].interFaceType === "api") {
            url = CONFIG.apiPath + apiName[uri].url;
        }else if(apiName[uri].interFaceType === "all") {
            url = fileNameFromHeader(data.get("url"), 2);
        }
        if(window.XMLHttpRequest){
            xhr = new XMLHttpRequest();
        } else {
            xhr = new ActiveXObject('Microsoft.XMLHTTP')
        }


        var type = method.toUpperCase();
        var random = Math.random();

        if(type == 'GET'){
            if(data){
                data = JSON.parse(data);
                if(apiName[uri].down) {
                    url = data.url;
                    xhr.responseType = "blob";
                    xhr.onload = function () {
                        if (this.status == 200) {
                            downloadFile(fileNameFromHeader(xhr.responseURL, 1), xhr.response);
                        }
                    }
                }else {
                    let index = 0;
                    for(let i in data) {
                        if(index === 0) {
                            url += '?' + i + '=' + data[i];
                            index ++;
                        }else {
                            url += '&' + i + '=' + data[i];
                        }
                    }
                    url += '&t=' + random;
                }
                xhr.open(type, url, true);
            } else {
                xhr.open(type, url + '?t=' + random, true);
            }
            if(apiName[uri].headers) {
                xhr.setRequestHeader("Access-Control-Allow-Origin", "*");
                xhr.setRequestHeader("Access-Control-Allow-Method", "POST,GET");
                for(let item of apiName[uri].headers) {
                    xhr.setRequestHeader(item.key, item.value);
                }
            }
            xhr.send();

        } else if(type == 'POST' || type == 'PUT'){
            if(apiName[uri].postType) {
                data = JSON.parse(data);
                let index = 0;
                for(let i in data) {
                    if(index === 0) {
                        url += '?' + i + '=' + data[i];
                        index ++;
                    }else {
                        url += '&' + i + '=' + data[i];
                    }
                }
                data = null;
            }
            xhr.open(type, url, true);
            xhr.setRequestHeader("Access-Control-Allow-Origin", "*");
            xhr.setRequestHeader("Access-Control-Allow-Method", "POST,GET");
            if(apiName[uri].headers) {
                for(let item of apiName[uri].headers) {
                    xhr.setRequestHeader(item.key, item.value);
                }
            }
            xhr.send(data);
        }

        xhr.onreadystatechange = function(){
            if(xhr.readyState == 4){
                let timeOut = (new Date() - startTime) / 1000;
                if(xhr.status === 200 && timeOut <= timeEnd || apiName[uri].interFaceType === "all"){

                    if(apiName[uri].down){
                        success(xhr.response);
                    }else {
                        try {
                            let res  = JSON.parse(xhr.responseText);
                            if(res.code && res.code === 200 ||  apiName[uri].interFaceType === "all") {
                                success(res);
                            }else {
                                vuethis.$message.error(res.message);
                            }
                        } catch (error) {
                            if(xhr.responseText.indexOf("<!DOCTYPE html>")!= -1) {
                                setTimeout(()=> {
                                    localStorage.ajaxTimeLock = true;
                                },5000)
                                if(localStorage.ajaxTimeLock) {
                                    vuethis.$message.error("登录身份失效，请重新登录");
                                    setTimeout(()=> {
                                        location.href = process.env.LOGO_URL;
                                    },3000)
                                }
                            }
                        }
                    }
                    // vuethis.$Progress.finish();
                } else {
                    setTimeout(()=> {
                        localStorage.ajaxTimeLock = true;
                    },5000)
                    if(localStorage.ajaxTimeLock) {
                        localStorage.ajaxTimeLock = false;
                        if(timeOut > timeEnd) {
                            vuethis.$message.error("请求超时");
                        } else {
                            vuethis.$message.error("请求失败");
                        }
                        // vuethis.$Progress.finish();
                    }
                    if(failed) {
                        failed(xhr.status);
                    }
                }
            }
        }
    }
  });

function fileNameFromHeader(disposition, type) {
    if (disposition) {
        let index = disposition.lastIndexOf("\/"); 
        return (type === 1)?disposition.substring(index + 1, disposition.length):disposition.split(".com")[0]+'.com';
    }
    return "undefine_file";
}

function downloadFile(fileName, content) {
    var aLink = document.createElement('a');
    var blob = new Blob([content]);
    var evt = document.createEvent("MouseEvents");
    evt.initEvent("click", true, true);
    if (fileName) {
        aLink.download = fileName;
    }
    aLink.target = "_blank";
    aLink.href = URL.createObjectURL(blob);
    aLink.dispatchEvent(evt);
}

  export default api;